﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Common;
using HIWSystem.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace HIWSystem.ViewModel
{
    public class LabelConfigViewModel : ViewModelBase
    {
        private bool isFirstFilterPN = true;
        ObservableCollection<PartNumberEntity> backupPNs = null;
        #region 属性
        private ObservableCollection<PartNumberEntity> pns;
        /// <summary>
        /// 机种实体集合
        /// </summary>
        public ObservableCollection<PartNumberEntity> PNs
        {
            get { return pns; }
            set { pns = value; this.RaisePropertyChanged(() => PNs); }
        }
        private PartNumberEntity selectedPartNumber;
        /// <summary>
        /// 选择的机种实体
        /// </summary>
        public PartNumberEntity SelectedPartNumber
        {
            get { return selectedPartNumber; }
            set { selectedPartNumber = value; this.RaisePropertyChanged(() => SelectedPartNumber); }
        }
        private string pn;
        /// <summary>
        /// 机种
        /// </summary>
        public string PN
        {
            get { return pn; }
            set { pn = value; this.RaisePropertyChanged(() => PN); }
        }
        private bool isOpenComboPNDropDown;
        /// <summary>
        /// 是否打开机种下拉框选项卡
        /// </summary>
        public bool IsOpenComboPNDropDown
        {
            get { return isOpenComboPNDropDown; }
            set { isOpenComboPNDropDown = value; this.RaisePropertyChanged(() => IsOpenComboPNDropDown); }
        }
        private string searchPNText;
        /// <summary>
        /// 机种下拉框中输入的文本内容
        /// </summary>
        public string SearchPNText
        {
            get { return searchPNText; }
            set { searchPNText = value; this.RaisePropertyChanged(() => SearchPNText); }
        }
        private ObservableCollection<LabelTemplateEntity> templates;
        /// <summary>
        /// 模版实体集合
        /// </summary>
        public ObservableCollection<LabelTemplateEntity> Templates
        {
            get { return templates; }
            set { templates = value; this.RaisePropertyChanged(() => Templates); }
        }
        private PartNumberEntity selectedTemplate;
        /// <summary>
        /// 选择的模版实体
        /// </summary>
        public PartNumberEntity SelectedTemplate
        {
            get { return selectedTemplate; }
            set { selectedTemplate = value; this.RaisePropertyChanged(() => SelectedTemplate); }
        }
        private string template;
        /// <summary>
        ///模版
        /// </summary>
        public string Template
        {
            get { return template; }
            set { template = value; this.RaisePropertyChanged(() => Template); }
        }
        private bool isOpenComboTemplateDropDown;
        /// <summary>
        /// 是否打开模版下拉框选项卡
        /// </summary>
        public bool IsOpenComboTemplateDropDown
        {
            get { return isOpenComboTemplateDropDown; }
            set { isOpenComboTemplateDropDown = value; this.RaisePropertyChanged(() => IsOpenComboTemplateDropDown); }
        }
        private string searchTemplateText;
        /// <summary>
        /// 模版下拉框中输入的文本内容
        /// </summary>
        public string SearchTemplateText
        {
            get { return searchTemplateText; }
            set { searchTemplateText = value; this.RaisePropertyChanged(() => SearchTemplateText); }
        }
        private ObservableCollection<TemplateVariableEntity> variables;
        //标签变量集合
        public ObservableCollection<TemplateVariableEntity> Variables
        {
            get { return variables; }
            set { variables = value; this.RaisePropertyChanged(() => Variables); }
        }
        private ObservableCollection<string> templateTypes;
        //模版类型《Label/PACKING》
        public ObservableCollection<string> TemplateTypes
        {
            get { return templateTypes; }
            set { templateTypes = value; this.RaisePropertyChanged(() => TemplateTypes); }
        }
        private string templateType;
        /// <summary>
        /// 选择的模版类型
        /// </summary>
        public string TemplateType
        {
            get { return templateType; }
            set { templateType = value; this.RaisePropertyChanged(() => TemplateType); }
        }
        private ObservableCollection<LabelTemplateVariableEntity> labelTemplateVariables;

        public ObservableCollection<LabelTemplateVariableEntity> LabelTemplateVariables
        {
            get { return labelTemplateVariables; }
            set { labelTemplateVariables = value;this.RaisePropertyChanged(() => LabelTemplateVariables); }
        }
        private ObservableCollection<PartNumberTemplateVariableEntity> partNumberTemplateVariables;

        public ObservableCollection<PartNumberTemplateVariableEntity> PartNumberTemplateVariables
        {
            get { return partNumberTemplateVariables; }
            set { partNumberTemplateVariables = value; this.RaisePropertyChanged(() => PartNumberTemplateVariables); }
        }
        #endregion

        #region 命令
        private RelayCommand loadedPageCommand;

        public RelayCommand LoadedPageCommand
        {
            get
            {
                return loadedPageCommand ?? new RelayCommand(LoadedPage);
            }
            set { loadedPageCommand = value; }
        }
        private RelayCommand<string> templateSelectionChangedCmd;

        public RelayCommand<string> TemplateSelectionChangedCmd
        {
            get
            {
                return templateSelectionChangedCmd ?? new RelayCommand<string>(TemplateSelectedChangedHandler);
            }
            set { templateSelectionChangedCmd = value; }
        }
        private RelayCommand<TemplateVariableEntity> variableCheckedCmd;

        public RelayCommand<TemplateVariableEntity> VariableCheckedCmd
        {
            get { return variableCheckedCmd ?? new RelayCommand<TemplateVariableEntity>(VariableCheckedHandler); }
            set { variableCheckedCmd = value; }
        }
        private RelayCommand<LabelTemplateVariableEntity> labelTemplateVarDataGridDoubleClickCmd;

        public RelayCommand<LabelTemplateVariableEntity> LabelTemplateVarDataGridDoubleClickCmd
        {
            get {
                return labelTemplateVarDataGridDoubleClickCmd ?? new RelayCommand<LabelTemplateVariableEntity>(LabelTemplateVarDataGridDoubleClickHandler);
            }
            set { labelTemplateVarDataGridDoubleClickCmd = value; }
        }
        private RelayCommand searchCmd;

        public RelayCommand SearchCmd
        {
            get { 
                return searchCmd??new RelayCommand(Search); }
            set { searchCmd = value; }
        }
        
        private RelayCommand buildCmd;

        public RelayCommand BuildCmd
        {
            get
            {
                return buildCmd ?? new RelayCommand(Build);
            }
            set { buildCmd = value; }
        }

        private RelayCommand bindTemplateVariableCmd;

        public RelayCommand BindTemplateVariableCmd
        {
            get
            {
                return bindTemplateVariableCmd ?? new RelayCommand(BindTemplateVariableMap);
            }
            set { bindTemplateVariableCmd = value; }
        }

        #endregion

        #region 方法
        //页面加载
        private async void LoadedPage()
        {
             await FillTemplateTypes();
             await FillPNsToComboBox();
             await FetchAndFillLabelTemplate();
             await FetchAndFillLabelTemplateVariable();
        }
        //绑定机种、模版、模版变量之间的对应关系
        private async void Build()
        {
            var selectedEntity = PartNumberTemplateVariables?.Where(p => p.IsChecked == true);
            if (selectedEntity?.Count()>0)
            {
                await Task.Run(() => {
                    var strEntities= string.Join("|",selectedEntity.Select(p => p.PN + "," + p.Template + "," + p.Variable + "," + p.VariableValue).ToArray());
                    try
                    {
                        var result= BusinessProcess.AddLabelConfigInfos(strEntities);
                        if (result.Split('|')[0] == "OK")
                        {
                            MessageBox.Show("创建成功!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else {
                            MessageBox.Show("创建失败!"+result.Split('|')[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("创建标签对应关系的时候发生错误:"+ex.Message,"软件温馨提示",MessageBoxButton.OK,MessageBoxImage.Error);
                        throw new Exception(ex.Message);
                    }
                });
            }
        }
        //绑定模版和变量的对应关系
        private void BindTemplateVariableMap()
        {
            if (LabelTemplateVariables?.Count() > 0)
            {
                var strTemplateVars = string.Join("|", LabelTemplateVariables.Select(e => e.Template +","+ e.Variable).ToArray());
                try
                {
                    var result = BusinessProcess.AddTemplateVariableMap(strTemplateVars);
                    if (result.Split('|')[0] == "OK")
                    {
                        MessageBox.Show("创建成功!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        MessageBox.Show("创建失败!" + result.Split('|')[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("创建标签对应关系的时候发生错误:" + ex.Message, "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Error);
                    throw new Exception(ex.Message);
                }

            }
            else
            {
                MessageBox.Show("没有添加模版和变量基础参数", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

        }

        private void Search()
        {
            if ((PN??"")=="")
            {
                MessageBox.Show("请选择机种信息","软件温馨提示",MessageBoxButton.OK,MessageBoxImage.Warning);
                return;
            }
            if ((Template ?? "") == "")
            {
                MessageBox.Show("请选择模版信息", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if ((TemplateType?? "") == "")
            {
                MessageBox.Show("请选择模版类型信息", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            //获取模版和模版参数之间的对应关系
            var dtTemplateVariableSource = BusinessProcess.GetLabelTemplateVariableMapByTemplate(Template);
            if (dtTemplateVariableSource.Rows.Count==0)
            {
                MessageBox.Show("没有查询到模版对应的模版变量，请先添加对应关系然后再点击查询.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            //获取机种、模版、模板变量之间的对应关系
            var dtPartNumberTemplateVariableMapSource = BusinessProcess.GetPartNumberTemplateVariable(PN, Template, TemplateType);
            //下面的大致思想:遍历模版和参数之间的应该关系，如果这个机种已经添加了模版和变量直接的对应关系，就在前台数据表中的选择列打勾，没有的就不选中。
            //通过用户勾选选择列，建立对应关系。
            PartNumberTemplateVariables = new ObservableCollection<PartNumberTemplateVariableEntity>();
            foreach (DataRow drTemplateVar in dtTemplateVariableSource.Rows)
            {
                var entity = new PartNumberTemplateVariableEntity();
                var drMatchSource= dtPartNumberTemplateVariableMapSource.AsEnumerable().FirstOrDefault(drPNTemplateVar => drPNTemplateVar["TemplateName"].ToString().Equals(drTemplateVar["TemplateName"].ToString()) &&
                                                                                          drPNTemplateVar["VariableName"].ToString().Equals(drTemplateVar["VariableName"].ToString()));
                if (drMatchSource != null)
                {
                    entity.PN = drMatchSource["PN"].ToString();
                    entity.Template = drMatchSource["TemplateName"].ToString();
                    entity.Variable = drMatchSource["VariableName"].ToString();
                    entity.VariableValue = drMatchSource["VariableValue"].ToString();
                    entity.IsChecked = true;
                }
                else
                {
                    entity.PN = PN;
                    entity.Template = Template;
                    entity.Variable = drTemplateVar["VariableName"].ToString();
                    entity.VariableValue = "";
                    entity.IsChecked = false;
                }
                PartNumberTemplateVariables.Add(entity);
            }
        }
        //标签模版变量数据网格鼠标双击事件
        private void LabelTemplateVarDataGridDoubleClickHandler(LabelTemplateVariableEntity entity)
        {
            if (entity != null)
            {
                var dialogResult = MessageBox.Show(string.Format("确定要删除模版【{0}】的参数【{1}】", entity.Template, entity.Variable), "软件温馨提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                if (dialogResult == MessageBoxResult.OK)
                {
                    LabelTemplateVariables.Remove(entity);
                }
            }
        }

        //变量选择改变事件
        private void VariableCheckedHandler(TemplateVariableEntity variableEntity)
        {
            if (variableEntity != null)
            {
                if ((Template ?? "") != "")
                {
                    var isExists = LabelTemplateVariables.Count(tv => tv.Variable.Equals(variableEntity.Variable)) > 0 ? true : false;
                    if (!isExists)
                    {
                        var entity = new LabelTemplateVariableEntity { Template = Template, Variable = variableEntity.Variable };
                        LabelTemplateVariables.Add(entity);
                    }
                }
            }
        }

        private void TemplateSelectedChangedHandler(string template)
        {
            if (template != null)
            {
                var dtSource = BusinessProcess.GetLabelTemplateVariableMapByTemplate(template);
                LabelTemplateVariables = new ObservableCollection<LabelTemplateVariableEntity>();
                foreach (DataRow dr in dtSource.Rows)
                {
                    var entity = new LabelTemplateVariableEntity
                    {
                        Template = dr["TemplateName"].ToString() ?? "",
                        Variable = dr["VariableName"].ToString() ?? ""
                    };
                    LabelTemplateVariables.Add(entity);
                }
            }
        }
        private async Task FillPNsToComboBox()
        {
            await Task.Run(() =>
            {
                DataTable dtPNs = new DataTable();
                dtPNs = BusinessProcess.GetPNs(EnumPNType.All);
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    PNs = new ObservableCollection<PartNumberEntity>();
                    for (int i = 0; i < dtPNs.Rows.Count; i++)
                    {
                        PNs.Add(new PartNumberEntity
                        {
                            PN = dtPNs.Rows[i]["PartNumber"].ToString()
                        });
                    }
                }));

            });

        }
        //检索并填充模版信息
        private async Task FetchAndFillLabelTemplate()
        {
            DataTable dtTemplate = new DataTable();
            await Task.Run(() =>
             {
                 dtTemplate = BusinessProcess.GetLabelTemplate();
                 Templates = new ObservableCollection<LabelTemplateEntity>();
                 Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                 {
                     LabelTemplateEntity templateEntity;
                     for (int i = 0; i < dtTemplate.Rows.Count; i++)
                     {
                         templateEntity = new LabelTemplateEntity
                         {
                             Id = Convert.ToInt32(dtTemplate.Rows[i]["Id"].ToString() ?? "0"),
                             TemplateName = dtTemplate.Rows[i]["TemplateName"].ToString() ?? "",
                             Size = dtTemplate.Rows[i]["Size"].ToString() ?? "",
                             IsChecked = false,
                             PrintType = dtTemplate.Rows[i]["TemplateType"].ToString() ?? "",
                             VariableNum = Convert.ToInt32(dtTemplate.Rows[i]["VariableNum"].ToString() ?? "0")
                         };
                         Templates.Add(templateEntity);
                     }
                 }));
             });
        }
        //检索并填充模版变量
        private async Task FetchAndFillLabelTemplateVariable()
        {
            DataTable dtTemplateVariable = new DataTable();
            await Task.Run(() =>
            {
                dtTemplateVariable = BusinessProcess.GetLabelTemplateVariable();
                Variables = new ObservableCollection<TemplateVariableEntity>();
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    TemplateVariableEntity templateVariableEntity;
                    for (int i = 0; i < dtTemplateVariable.Rows.Count; i++)
                    {
                        templateVariableEntity = new TemplateVariableEntity
                        {
                            Id = Convert.ToInt32(dtTemplateVariable.Rows[i]["Id"].ToString() ?? "0"),
                            Variable = dtTemplateVariable.Rows[i]["VariableName"].ToString() ?? "",
                            IsChecked = false
                        };
                        Variables.Add(templateVariableEntity);
                    }
                }));
            });
        }
        /// <summary>
        /// 筛选机种下拉列表框中的数据
        /// </summary>
        private void FilterPN()
        {

            IsOpenComboPNDropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (isFirstFilterPN)
            {
                backupPNs = new ObservableCollection<PartNumberEntity>();
                backupPNs = PNs;
                isFirstFilterPN = false;
            }
            if (!string.IsNullOrEmpty(SearchPNText))
            {
                IEnumerable<PartNumberEntity> partNumberEntities = PNs.Where(s => s.PN.ToUpper().Contains(SearchPNText.ToUpper()));
                PNs = new ObservableCollection<PartNumberEntity>();
                foreach (var p in partNumberEntities)
                {
                    PNs.Add(p);
                }
            }
            else
            {
                PNs = backupPNs;
            }

        }
        /// <summary>
        /// 填充模版类型
        /// </summary>
        private async Task FillTemplateTypes()
        {
            await Task.Run(() =>
            {
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    TemplateTypes = new ObservableCollection<string>() { "Label", "Packing" };
                }));

            });
        }

        #endregion
    }
}
